<?php

namespace Admin\Controllers;

use Forms\LoginForm;
use Forms\EdituserForm;
use Forms\UserForm;
use Models\Users;
use Models\Transactions;
use Forms\SearchForm;

class UserController extends ControllerBase {

    public function indexAction() {
        
    }

    public function loginAction() {
        $form = new LoginForm();
        try {
            if (!$this->request->isPost()) {

                if ($this->auth->hasRememberMe()) {
                    $this->auth->loginWithRememberMe();
                    return false;
                }
            } else {
                //valdate and print error in LoginForm function messages
                if ($form->isValid($this->request->getPost()) == true) {

                    $this->auth->check(array(
                        'username' => $this->request->getPost('username'),
                        'password' => $this->request->getPost('password'),
                        'remember' => $this->request->getPost('remember')
                    ));

                    if ($this->request->getQuery('url') == true) {
                        var_dump($this->request->getQuery('url'));
                        header('Location:' . $this->request->getQuery('url'));
                        return false;
                    }
                    header('Location: index');
                    return false;
                }
            }
        } catch (Exception $e) {
            $this->flash->error($e->getMessage());
        }
        $this->view->form = $form;
    }

    public function resetpasswordAction() {
        echo 'Reset password form';
    }

    public function logoutAction() {
        $this->auth->remove();
        return $this->response->redirect();
    }

    public function alluserAction() {
        $form = new SearchForm();
        $currentPage = (int) $this->request->getPost('page');
        if (!$currentPage) {
            $currentPage = 1;
        }
        $limit = $this->request->getPost('limit');
        if (!$limit) {
            $limit = 10;
        }
        $query = Users::query()
                ->where('1=1');

        if ($this->request->getPost('role')) {
            $query->andwhere('role_id = \'' . ($this->request->getPost('role')) . '\'');
        }
        if ($this->request->getPost('text')) {
            $query->andwhere('Models\Users.username LIKE \'%' . ($this->request->getPost('text')) . '%\'');
        }
        $users = $query->execute();
        $pagination = new \Phalcon\Paginator\Adapter\Model(
                array(
            "data" => $users,
            "limit" => $limit,
            "page" => $currentPage
        ));
        $this->view->users = $pagination->getPaginate();
        $this->view->form = $form;
    }

    public function edituserAction() {
        $form = new EdituserForm();
        $id = $this->dispatcher->getParam("id");
        $user = Users::findFirstById($id);
        if ($user) {
            $password = $user->password;
            $user->password = '';
            $form = new EdituserForm($user);
            if ($this->request->isPost()) {
                $request = $this->request->getPost();
                $request['username'] = $user->username;
                if ($form->isValid($request)) {
                    $user->address = $this->request->getPost('address');
                    $user->fullName = $this->request->getPost('fullName');
                    $user->points = $this->request->getPost('points');
                    $user->balance = $this->request->getPost('balance');
                    $user->role_id = $this->request->getPost('role_id');
                    $user->updatetime = date('Y-m-d H:i:s');
                    if ($this->request->getPost('password')) {
                        $user->password = $this->security->hash($this->request->getPost('password'));
                    } else {
                        $user->password = $password;
                    }
                    if ($user->save()) {
                        $form->appendMessage("Cập nhật thành công", "edit_info", null);
                    }
                    foreach ($user->getMessages() as $value) {
                        $form->appendMessage($value, "edit_info", null);
                    }
                }
            }
            $this->view->form = $form;
        } else {
            $this->dispatcher->forward(array(
                'module' => 'admin',
                'controller' => 'error',
                'action' => 'notAvailable'
            ));
        }
    }

    public function adduserAction() {
        $form = new UserForm();
        if ($this->request->isPost()) {
            if ($form->isValid($this->request->getPost())) {
                $user = new Users();
                $user->assign(array(
                    'username' => $this->request->getPost('username'),
                    'email' => $this->request->getPost('email'),
                    'address' => $this->request->getPost('address'),
                    'fullName' => $this->request->getPost('fullName'),
                    'points' => $this->request->getPost('points'),
                    'balance' => $this->request->getPost('balance'),
                    'role_id' => $this->request->getPost('role_id'),
                    'updatetime' => date('Y-m-d H:i:s'),
                    'expired' => date('Y-m-d'),
                    'password' => $this->security->hash($this->request->getPost('password')),
                ));
                if ($user->save()) {
                    $form->appendMessage("Thêm user thành công", "adduser_info", null);
                }
                foreach ($user->getMessages() as $value) {
                    $form->appendMessage($value, "adduser_info", null);
                }
            }
        }
        $this->view->form = $form;
    }

    public function deleteuserAction() {
        $ids = $this->request->getPost('ids');
        if ($ids) {
            $ids_str = implode(',', $ids);
            $users = Users::find("id IN ($ids_str)");
            foreach ($users as $user) {
                if (!$user->delete()) {
                    echo "Cannot delet user $user->id<br>";
                }
            }
        }
        $this->view->disable();
    }

    public function exchangeAction() {
        $form = new SearchForm();
        $currentPage = (int) $this->request->getPost('page');
        if (!$currentPage) {
            $currentPage = 1;
        }
        $limit = $this->request->getPost('limit');
        if (!$limit) {
            $limit = 10;
        }
        $query = $this->modelsManager->createBuilder()
                ->columns(array(
                    'Models\Transactions.id',
                    'Models\Transactions.user_id',
                    'Models\Transactions.date',
                    'Models\Transactions.note',
                    'Models\Transactions.money',
                    'Models\Transactions.balance_change',
                    'Models\Transactions.type',
                    'Users.username Username',
                    'Users.email Email',
                ))
                ->from('Models\Transactions')
                ->leftjoin('Models\Users', 'Models\Transactions.user_id = Users.id', 'Users')
                ->orderby('Models\Transactions.date DESC')
                ->where('1=1');

        if ($this->request->getPost('time')) {
            switch ($this->request->getPost('time')) {
                case '1' :
                    $query->andwhere('DATE(Models\Transactions.date) = CURDATE()');
                    break;
                case '2' :
                    $query->andwhere('WEEK(Models\Transactions.date) = WEEK(CURDATE())');
                    $query->andwhere('YEAR(Models\Transactions.date) = YEAR(CURDATE())');
                    break;
                case '3' :
                    $query->andwhere('MONTH(Models\Transactions.date) = MONTH(CURDATE())');
                    $query->andwhere('YEAR(Models\Transactions.date) = YEAR(CURDATE())');
                    break;
            }
        }
        if ($this->request->getPost('text')) {
            $query->andwhere('Users.username LIKE \'%' . $this->request->getPost('text') . '%\'');
        }
        $transactions = $query->getQuery()->execute();

        $pagination = new \Phalcon\Paginator\Adapter\Model(
                array(
            "data" => $transactions,
            "limit" => $limit,
            "page" => $currentPage
        ));
        $this->view->transactions = $pagination->getPaginate();
        $this->view->form = $form;
    }

}
